<template>
  <div>
    <login-top middle-top="登录bilibili">
      <div slot="right" style="color:darkgrey; font-size: 14px;" @click="$router.push('/register')">切换到注册</div>
    </login-top>
    <login-text label="账号" placeholder="请输入账号" rules="^.{6,16}$" style="margin: 4.1vw 0"
                @inputChange="res=>this.model.username=res"></login-text>
    <login-text label="密码" placeholder="请输入密码" rules="^.{6,16}$" type="password"
                @inputChange="res=>this.model.password=res"></login-text>
    <login-button btn-text="登录" style="margin: 4vw 3vw" @registerSubmit="registerSubmit"></login-button>
  </div>
</template>

<script>
import LoginTop from '@/components/common/LoginTop'
import LoginText from '@/components/common/LoginText'
import LoginButton from '@/components/common/LoginButton'

export default {
  data() {
    return {
      model: {
        username: '',
        password: ''
      }

    }
  },
  components: {
    LoginTop,
    LoginText,
    LoginButton
  },
  methods: {
    async registerSubmit() {
      let regex = /^.{6,16}$/
      if (regex.test(this.model.username) && regex.test(this.model.password)) {
        const res = await this.$http.post('/login', {
          name: this.model.name,
          username: this.model.username,
          password: this.model.password
        })
        this.$msg.success(res.data.msg)
        await this.AjaxInsert()
      } else {
        this.$msg.fail('格式不正确，请重新输入')
      }
    },
    async AjaxInsert() {
      if (this.model.username && this.model.password) {
        const res = await this.$http.post('/login', this.model)
        this.$msg.fail(res.data.msg)
        console.log(res)
        if (res.data.code === 301 || res.data.code === 302) {
          return
        }
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('id', res.data.id)
        setTimeout(() => {
          this.$router.push('/userinfo')
        }, 1000)
      } else {
        this.$msg.fail('格式不正确，请重新输入')
      }
    }
  }
}

</script>

